<template>
  <div class="card-out-container">
    <a-spin :spinning="spinning">
      <a-row class="mb-15">
        <a-col :span="6">
          <a-button type="primary" @click="exportTable" class="mr-10" :disabled="!(queryParam.time || hourList.length > 0)">导出</a-button>
          <!--<a-button type="primary" ghost @click="printTable">打印</a-button>-->
        </a-col>
        <a-col :span="18" class="full-width flex-right">
          <a-form layout="inline">
            <!--<a-form-item   :label="$t('basicData.styleNo')" required>-->
            <!--  <a-select v-model:value="queryParam.styleNo" :placeholder="$t('common.pleaseSelect')" allowClear  show-search :filter-option="filterOption" >-->
            <!--    <a-select-option v-for="item in  styleList" :key="item.key" :value="item.styleNo">{{item.styleNo}}</a-select-option>-->
            <!--  </a-select>-->
            <!--</a-form-item>-->
            <a-form-item :label="$t('common.selectDate')" :rules="[{ required: true, message: '请选择日期' }]">
              <a-date-picker v-model:value="queryParam.time" @change="changeDate" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD"/>
              <!--<a-range-picker v-model:value="queryParam.time" :placeholder="[$t('common.startDate'), $t('common.endDate')]" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD"  />-->
            </a-form-item>
            <a-form-item :label="$t('other.selectTime')" :rules="[{ required: true, message: $t('other.selectTime') }]">
              <a-time-range-picker  v-model:value="queryParam.time1" :showNow="false"  format="HH" />
              <!--<a-date-picker v-model:value="queryParam.time" @change="changeDate" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD"/>-->
            </a-form-item>

            <a-form-item>
              <a-space>
                <a-button class="mr-10" type="primary" @click="selectHour" :disabled="!queryParam.time1">选择时段</a-button>
                <!--<a-button class="mr-10" type="primary" :disabled="!queryParam.time" @click="selectHour" >选择时段</a-button>-->
              </a-space>
              <a-space>
                <a-button
                  type="primary"
                  @click="loadData"
                  :disabled="!(queryParam.time || hourList.length > 0)"
                  >{{ $t('common.search') }}</a-button
                >
              </a-space>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>

      <a-table
        rowKey="id"
        :loading="loading"
        bordered
        size="small"
        :dataSource="dataList"
        :columns="header"
        :scroll="{ y: 'calc(100vh - 320px)' }"
        :pagination="false"
        @change="handleTableChange"
        :rowSelection="null"
        :showMore="showMore"
        :operateMargin="true"
        :drag="false"
        storeTableName="outputStationHourFlow"
        tableColumnsSort="outputStationHourFlowSort"
      >
        <template #headerCell="{ column }">
          <template v-if="column.key === 'other'">
            <span class="text-red"></span>{{ headGroupTitle }}
          </template>
        </template>
        <!--<template #bodyCell="{ record , column }">
          <template v-if="column.key === 'staffNo'" >
            <span class="code-link"> ( {{ record.staffNo }}) {{ record.staffName }} </span>
            &lt;!&ndash;<span class="code-link"> {{ record.staffNo }} {{ record.staffName }} </span>&ndash;&gt;
          </template>
        </template>
        <template #summary>
          <a-table-summary-row>
            <a-table-summary-cell :col-span="2" align="right">总计：</a-table-summary-cell>
            <a-table-summary-cell align="center">{{ quantityTatol1 }} </a-table-summary-cell>
            <a-table-summary-cell align="center">{{ quantityTatol2 }} </a-table-summary-cell>
            <a-table-summary-cell align="center">{{ quantityTatol3 }} </a-table-summary-cell>
          </a-table-summary-row>
        </template>-->
        <template
          #customFilterDropdown="{
            setSelectedKeys,
            selectedKeys,
            confirm,
            clearFilters,
            column,
          }"
        >
          <filterDropdown
            :setSelectedKeys="setSelectedKeys"
            :selectedKeys="selectedKeys"
            :confirm="confirm"
            :clearFilters="clearFilters"
            :column="column"
            :initialList="header[0]?.children"
          ></filterDropdown>
        </template>
      </a-table>

      <div style="display: none">
        <a-table
          id="printId"
          :loading="loading"
          bordered
          size="small"
          :dataSource="printDataList"
          :columns="printColumnsArr"
          :pagination="false"
        >
        </a-table>
      </div>
    </a-spin>
    <OtherModal ref="otherModalRef" @ok="otherModalOk" />
  </div>
</template>
<script>
import { ListMixinPm } from "@/mixin/listMixinPm.js";
// import { columns } from './modules/config.js'
import { cloneDeep } from "lodash";
import {
  filterObj,
  startTimeValue,
  getLocalStorage,
  toLineName,
} from "@/utils";
import { mapState } from "vuex";
import { store } from "@/store";
import axios from "@/utils/request";
import printJS from "print-js";
import { message } from "ant-design-vue";
// import { HourDialog } from "./modules/hourDialog.vue";
import OtherModal from "./modules/otherModal.vue";
import filterDropdown from "@/components/filterDropdown/filterDropdown.vue";

export default {
  name: "outputStationHourFlow",
  mixins: [ListMixinPm],
  components: {
    OtherModal,
    filterDropdown,
  },
  data() {
    return {
      // columns: columns,
      spinning: false,
      printDataList: [],
      url: {
        list: "/api/report/get-station-hour-hanger",
        exportUrl: "/api/report/export-station-hour-hanger",
      },
      columnsArr: [],
      columnsTitleArr: [],
      printColumnsArr: [],
      queryParam: {},
      showData: false,

      headGroupTitle: "", // 款式 + 时间
      header: [], // 自定义表头
      dataList: [], //返回数据
      hourListArray: [], // 时间 对象数组
      hourList: [], //时间 0 1 2 3

      // quantityTatol1: 0,
      // quantityTatol2: 0,
      // quantityTatol3: 0,
      // data : [...Array(10)].map((_, i) => ({
      //   lineNo: i,
      //   staffNo: 'John Brown',
      //   name1: '工序名Lake Park',
      //   name2: i + 1,
      //   name3: i+'C',
      // }))
    };
  },
  async created() {
    // await store.dispatch('getStyle')
    await store.dispatch("getWater");
    // await store.dispatch('getUser')
    this.initColoum();
    this.showData = true;
  },
  computed: {
    ...mapState({
      // styleList: state => state.normalData.styleList,
      waterList: (state) => state.normalData.waterList,
      // userList: state => state.normalData.userList,
    }),
  },
  methods: {
    changeDate() {
      let valueList = getLocalStorage("hourList")
        ? getLocalStorage("hourList")
        : this.hourListArray;
      this.hourList =
        valueList &&
        valueList.filter((i) => i.checked === true).map((item) => item.value);
    },
    selectHour() {
      this.$refs.otherModalRef.open();
    },
    otherModalOk(valueList) {
      this.hourListArray = valueList;
      this.hourList =
        valueList &&
        valueList.filter((i) => i.checked === true).map((item) => item.value);
      // console.log(this.hourList)
      // console.log(valueList)
    },
    //  表头变更的搜索条件
    handleTableChange(pagination, filters, sorter) {
      ["lineNo"].forEach((i) => {
        this.queryParam[i] = (filters || {})[i];
      });
      if (Object.keys(sorter).length > 0) {
        this.isorter.field = sorter.order ? toLineName(sorter.field) : "";
        this.isorter.order = sorter.order
          ? sorter.order == "ascend"
            ? "asc"
            : "desc"
          : "";
      }
      this.ipagination = Object.assign(this.ipagination, pagination);
      this.loadData();
    },
    // 表头筛选
    initColoum() {
      // 流水线号 员工
      let columnsList = cloneDeep(this.header);
      columnsList[0] &&
        columnsList[0].children.forEach((i) => {
          if (i.dataIndex == "lineNo") {
            i.customFilterDropdown = true;
            i.filters = this.waterList.map((el) => ({
              text: el.lineNo,
              value: el.lineNo,
            }));
          }
        });
      this.header = columnsList;
    },
    getQueryParams() {
      // console.log(this.showData,'是否默认展示数据')
      // 临时取消
      if (!this.showData) return false;
      this.getColumnsList();
      let param = cloneDeep(this.queryParam);
      // console.log(this.queryParam)
      if (this.queryParam.time && this.queryParam.time.length) {
        param.queryTime = startTimeValue(this.queryParam.time);
        // param.endProductTime = endTimeValue(this.queryParam.time[1])
        this.queryParam.queryTime = startTimeValue(this.queryParam.time);
        // this.queryParam.endProductTime = endTimeValue(this.queryParam.time[1])
      } else {
        param.queryTime = null;
        // param.endProductTime = null
        this.queryParam.queryTime = null;
        // this.queryParam.endProductTime = null
      }
      delete param.time;
      param.sortingFields = this.isorter.field ? [this.isorter] : null;
      this.queryParam.sortingFields = this.isorter.field
        ? [this.isorter]
        : null;
      // param.pageNo = this.ipagination.current
      // param.pageSize = this.ipagination.pageSize
      //表头
      this.headGroupTitle = "" + this.queryParam.styleNo;
      if (this.queryParam.time) {
        this.headGroupTitle = this.queryParam.time;
      }
      param.lineNoList = this.queryParam.lineNo || [];
      // console.log(this.queryParam)
      let valueList = getLocalStorage("hourList")
        ? getLocalStorage("hourList")
        : this.hourListArray;
      this.hourList =
        valueList &&
        valueList.filter((i) => i.checked === true).map((item) => item.value);

      param.hourList = this.hourList;
      // console.log(param)
      return filterObj(param);
    },

    async printTable() {
      await this.getColumnsList();
      this.queryParam.pageNo = 1;
      this.queryParam.pageSize = 65335;
      const res = await axios.postAction(this.url.list, this.queryParam);
      if (!res.data) return;
      this.spinning = true;
      if (res) {
        this.printDataList = res.data.list;
        // console.log(this.printDataList)
        if (this.printDataList.length > 0) {
          setTimeout(() => {
            this.printTableData();
            this.spinning = false;
          }, 2000);
        } else {
          this.spinning = false;
        }
      }
    },
    //打印  请求做好的导出接口 变更数据展示
    printTableData() {
      printJS({
        printable: "printId", // 标签元素id
        type: "html",
        documentTitle: "[款式-员工-工序]",
        style:
          "#printId{width:100%;} " +
          " #printId .ant-table-thead>tr>th, #printId .ant-table-tbody>tr>td  {border: 1px solid #bcb8b8;border-collapse: collapse;} " +
          " #printId table{border-collapse: collapse;} ",
      });
    },
    async exportTable() {
      // await this.getColumnsList()
      let param = {
        pageNo: 1,
        pageSize: 65335,
        // columns:this.columnsArr ,
        // tables:this.columnsTitleArr,
        queryTime: startTimeValue(this.queryParam.time),
        // sortingFields:this.queryParam.sortingFields,
        lineNoList: this.queryParam.lineNo,
        hourList: this.hourList || [],
        // aaaa:this.queryParam,
      };
      // console.log(param)
      // this.exportExcels(this.url.exportUrl, '产量报表-款式-员工-工序', true,param)
      this.exportExcels(
        this.url.exportUrl,
        this.queryParam.styleNo,
        true,
        param
      );
    },
    async getColumnsList() {
      let colArr = [];
      let paramsArr = [];
      let titleArr = [];
      let hangerTrackTable = getLocalStorage("outputStationHourFlow")
        ? getLocalStorage("outputStationHourFlow")
        : this.header;
      // console.log(hangerTrackTable)
      if (hangerTrackTable[0] && hangerTrackTable[0].children.length > 0) {
        hangerTrackTable[0].children.forEach((item) => {
          if (!item.disappear) {
            paramsArr.push(item.dataIndex);
            titleArr.push(item.title);
            colArr.push(item);
          }
        });
      }
      this.columnsArr = paramsArr;
      this.columnsTitleArr = titleArr;
      this.printColumnsArr = colArr;
      // console.log(colArr,titleArr,paramsArr)
    },

    loadData() {
      if (!this.url.list) {
        message.error("请设置url.list属性!");
        return;
      }
      let params = this.getQueryParams();
      // console.log(params)
      if (!params) return;
      // 查询条件
      this.loading = true;
      axios
        .postAction(this.url.list, params)
        .then((res) => {
          if (res.success) {
            this.dataSource = res.data
              ? res.data.list
                ? res.data.list
                : Array.isArray(res.data)
                ? res.data
                : []
              : [];
            let headerArr = [
              {
                key: "other",
                value: "other",
                title: "-",
                children: [
                  {
                    title: "流水线号",
                    dataIndex: "lineNo",
                    key: "lineNo",
                    align: "center",
                    width: 120,
                  },
                  {
                    title: "站号",
                    dataIndex: "stationNo",
                    key: "stationNo",
                    align: "center",
                    width: 120,
                  },
                ],
              },
            ];
            let hourList = getLocalStorage("hourList")
              ? getLocalStorage("hourList")
              : this.hourListArray;
            hourList &&
              hourList
                .filter((record) => record.checked === true)
                .forEach((item, i) => {
                  if (item.checked) {
                    headerArr[0].children.push({
                      title: item.label,
                      dataIndex: "hour" + i,
                      key: "hour" + i,
                      align: "center",
                      width: 120,
                    });
                  }
                });
            headerArr[0].children.push(
              {
                title: "其他时间",
                dataIndex: "otherNumber",
                key: "otherNumber",
                align: "center",
                width: 120,
              },
              {
                title: "合计",
                dataIndex: "totalNumber",
                key: "totalNumber",
                align: "center",
                width: 120,
              }
            );
            // console.log(headerArr)
            this.header = headerArr;

            let tempArr = [];
            let dataListArr = [];
            tempArr = cloneDeep(this.dataSource);
            tempArr.forEach((item, i) => {
              item.hourNumberList.forEach((item2, j) => {
                item["hour" + j] = item2;
              });
              if (i == tempArr.length - 1 && item.stationNo == null) {
                item["stationNo"] = "总计";
              }
              dataListArr.push(item);
            });
            // console.log(dataListArr)
            this.dataList = dataListArr;
            // console.log(this.header)
            // console.log(this.dataList)
            // res.data && (this.ipagination.total = res.data.total || 0);
          }
          this.initColoum();
          this.getColumnsList();
          this.loading = false;
          this.selectedRowKeys = [];
        })
        .finally(() => {
          this.loading = false;
          this.tableKey = Math.random();
        });
      if (this.storeName) {
        if (typeof this.storeName == "string") {
          store.dispatch(this.storeName);
        } else if (Array.isArray(this.storeName)) {
          this.storeName.map((i) => {
            store.dispatch(i);
          });
        }
      }
    },
  },
};
</script>
